package lium.lbs.lbsim.jgchat.activity;

import android.util.Log;
import com.google.gson.Gson;
import com.lmlibrary.Constants;
import com.lmlibrary.bean.ResponseBean;
import com.lmlibrary.exception.MyException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.utils.OkLogger;
import lium.lbs.lbsim.base.BaseParamMap;
import lium.lbs.lbsim.utils.ToastUtils;

import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.HashMap;

public class BaseController {

    public <T> void handleError(Response<T> response) {
        if (response == null) return;
        if (response.getException() != null) response.getException().printStackTrace();
        int code = response.code();
        if (code == 404) {
            Log.d("JsonCallback", "404 当前链接不存在");
        }
        Throwable exception = response.getException();
        if (response.getException() instanceof SocketTimeoutException) {
            Log.d("JsonCallback", "请求超时");
        } else if (response.getException() instanceof SocketException) {
            Log.d("JsonCallback", "服务器异常");
        } else if (response.getException() instanceof MyException) { //个人自定义 异常 根据后台 约定值判断异常雷系
            switch (((MyException) response.getException()).getErrorBean().status) {
                case 1://约定的数据错误
                    ToastUtils.showToast(((MyException) response.getException()).getErrorBean().msg);
                    break;
                default:
                    ToastUtils.showToast(((MyException) response.getException()).getErrorBean().msg);
                    break;
            }

        }
    }

    public <T> void postData(String url, HashMap paramMap, Callback<T> callback) {
        BaseParamMap m = new BaseParamMap();
        m.putAll(paramMap);
        String paramJson = new Gson().toJson(m);
        OkLogger.e("参数:" + paramJson);
        PostRequest postRequest = OkGo.<ResponseBean<T>>post(Constants.Host + url)//
                .tag(this)
                .isMultipart(true); //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        postRequest.getParams().put(m);
        postRequest.execute(callback);
    }

}
